/**
 * 
 */
package com.effectiv.gooruda.business.impl;

import java.util.Locale;

import jodd.mail.Email;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;
import jodd.util.RandomStringUtil;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import com.effectiv.gooruda.business.api.AbstractBusinessService;
import com.effectiv.gooruda.business.api.TenantService;
import com.effectiv.gooruda.domain.Tenant;
import com.effectiv.gooruda.domain.Lov;
import com.effectiv.gooruda.repository.LovRepository;
import com.effectiv.gooruda.repository.TenantRespository;

/**
 * @author Dhrubo
 * 
 */
@Service
@Slf4j
public class TenantServiceImpl extends AbstractBusinessService<Tenant, String>
		implements TenantService {

	@Autowired
	private TenantRespository repository;

	@Autowired
	private LovRepository lovRepository;

	@Qualifier("passwordEncoder")
	@Autowired
	private PasswordEncoder encoder;
	
	@Autowired
    private SmtpServer smtpServer;
    
	@Autowired
    private TemplateEngine templateEngine;


	@Override
	public void register(Tenant tenant, Locale locale) {

		String random = RandomStringUtil.randomAlpha(8);
		log.info("###### Password = {}", random);

		String pwd = encoder.encodePassword(random, null);

		tenant.setPassword(pwd);
		Lov role = lovRepository.findByName("ROLE_COMPANY_ADMIN");
		tenant.setRole(role);

		log.info("###### Registering tenant = {}", tenant);

		tenant = repository.save(tenant);

		tenant.setPassword(random);
		
		log.info("###### Registered tenant = {}", tenant);
		
		
		log.info("###### Now sending email asynchronously.");
		

	}
	
	@Async
	public void sendMail(Tenant tenant, Locale locale, String templateName, String subject){
		//get html
		Context context = new Context(locale);
		context.setVariable(StringUtil.decapitalize(tenant.getClass().getSimpleName()), tenant);

        String html = templateEngine.process(templateName, context);

		//prepare email
		Email email = Email.create().from("info@gooruda.com")
				.to(tenant.getEmail())
				.subject(subject)
				.addHtml(html, "UTF-8");
		
		SendMailSession session = smtpServer.createSession();
        session.open();
        log.info("Sending email started.");
        session.sendMail(email);
        log.info("Send email.");
        session.close();
        log.info("End email session.");

	}

	@Override
	protected void initInternal() {
		setRepository(repository);
	}

	@Override
	public Tenant activate(String id, Locale locale) {
		Tenant tenant = repository.findOne(id);
		if (tenant != null) {
			tenant.setActive(true);
			super.update(tenant);
		}
		
		
		return tenant;
	}

}
